﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CMS.Services;
using CMS.BL.Entity;
using CMS.UI.Common;

namespace CMS.UI.Controllers
{
    public class BaseWebController : BaseController
    {
        private readonly IDomain DomainService;
        private readonly IUser UserService;

        public BaseWebController(IDomain domainService,
            IUser userService)
            : base(domainService)
        {
            this.DomainService = domainService;
            this.UserService = userService;
        }

        protected tbl_Basket FindBasket()
        {
            tbl_Basket basket = null;

            if (CookieManager.BasketCookie.HasValue)
            {
                basket = ECommerceService.GetBasketByID(CookieManager.BasketCookie.Value);
                if (basket == null)
                    return null;
                int customerID = basket.B_CustomerID;
                if (AdminUser != null && !AdminUser.IsAdmn && customerID != AdminUser.UserID)
                {
                    basket = ECommerceService.UpdateBasketCustomerID(AdminUser.UserID, basket.BasketID);
                }
                else if ((AdminUser == null && customerID > 0) || (AdminUser != null && AdminUser.IsAdmn && customerID > 0))
                {
                    basket = ECommerceService.UpdateBasketCustomerID(0, basket.BasketID);
                }
            } 
            else if (Request.IsAuthenticated && !AdminUser.IsAdmn)
            {
                var customer = UserService.GetCustomerByID(this.AdminUser.UserID);
                if (customer != null)
                {
                    basket = customer.tbl_Basket.OrderByDescending(c => c.B_LastAccessed).FirstOrDefault();
                    if (basket != null)
                    {
                        CookieManager.BasketCookie = basket.BasketID;
                    }
                }
            }

            return basket;
        }

        protected tbl_Orders FindOrder()
        {
            tbl_Orders order = null;
            if (Request.IsAuthenticated && !AdminUser.IsAdmn)
            {
                var customer = UserService.GetCustomerByID(this.AdminUser.UserID);
                if (customer != null)
                {
                    order = customer.tbl_Orders.OrderByDescending(c => c.OrderID).FirstOrDefault();
                }
            }

            return order;
        }
    }
}
